package dhm.com.hpx.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dhm.com.hpx.R;
import dhm.com.hpx.activity.MsgActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.GetManagerBean;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.Util;

/**
 * Created by admin
 * 2019/4/29
 * 所有订单适配器
 */
public class ManagerAdapter extends RecyclerView.Adapter<ManagerAdapter.ViewHolder> implements LoginContract.IView {

    private Context context;


    List<GetManagerBean.DataBean.ListDataBean> list = new ArrayList<>();

    private PressenterImpl pressenter;

    String uid = "";

    public ManagerAdapter(Context context, String uid) {
        this.context = context;
        this.uid = uid;
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
    }


    public void setList(List<GetManagerBean.DataBean.ListDataBean> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        ViewHolder viewHolder;
        View view = LayoutInflater.from(context).inflate(R.layout.recy_manager, null);
        viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {

        final String userType = SpUtils.getString(context, "userType");

        if (userType.equals("0")||userType.equals("4")){
            String[] split = list.get(i).getTel().split(";");
            String num="";
            for (int j = 0; j < split.length; j++) {
                num=num+split[j].substring(0,3)+"****"+split[j].substring(split[j].length()-4,split[j].length())+";";
            }
            num=num.substring(0,num.length()-1);
            viewHolder.phone.setText(num);
        }else {
            viewHolder.phone.setText(list.get(i).getTel());
        }


        if (list.get(i).getIs_export_mail()==0){
            viewHolder.img_num.setImageResource(R.mipmap.manager_num);
        }else {
            viewHolder.img_num.setImageResource(R.mipmap.btm_num);
        }

        if (list.get(i).getIs_phone()==0){
            viewHolder.img_phone.setImageResource(R.mipmap.manager_phone);
        }else {
            viewHolder.img_phone.setImageResource(R.mipmap.manager_phones);
        }

        if (list.get(i).getIs_sms()==0){
            viewHolder.img_msg.setImageResource(R.mipmap.manager_msg);
        }else {
            viewHolder.img_msg.setImageResource(R.mipmap.btm_msg);
        }

        if (list.get(i).getIscheck().equals("0")) {
            viewHolder.agree.setChecked(false);
        } else {
            viewHolder.agree.setChecked(true);
        }
        viewHolder.name.setText(list.get(i).getCompany_name());
        viewHolder.addr.setText(list.get(i).getProvince() + list.get(i).getCity() + list.get(i).getArea() + list.get(i).getAddress());

        viewHolder.agree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isPressed()) {
                    onClick.item(i, viewHolder.agree.isChecked());
                }
            }
        });

        viewHolder.img_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                switch (userType) {
                    case "0":
                        Toast.makeText(context, "暂无权限查看，请升级会员", Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(context, "您的会员已过期", Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "5":
                    default:


                        // 检查是否获得了权限（Android6.0运行时权限）
                        //权限没有获得
                        if (ContextCompat.checkSelfPermission(context,
                                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // 没有获得授权，申请授权
                            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context,
                                    Manifest.permission.CALL_PHONE)) {
                                // 返回值：
                                // 如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
                                // 如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
                                // 如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                                // 弹窗需要解释为何需要该权限，再次请求授权
                                Toast.makeText(context, "请授权拨打电话权限！", Toast.LENGTH_LONG).show();

                                // 帮跳转到该应用的设置界面，让用户手动授权
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                                intent.setData(uri);
                                context.startActivity(intent);
                            } else {
                                // 不需要解释为何需要该权限，直接请求授权
                                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE}, 100);
                            }
                        } else {
                            // 已经获得授权，可以打电话
                            CallPhone(i);
                        }
                }


            }
        });

        viewHolder.img_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (userType) {
                    case "0":
                        Toast.makeText(context, "暂无权限查看，请升级会员", Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(context, "您的会员已过期", Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "5":
                    default:

                        Map<String, String> map = new HashMap<>();
                        map.put("token",Constant.TOKEN);
                        map.put("uid", uid);
                        map.put("type", "4");
                        map.put("customer_id", list.get(i).getCustomer_id() + "");
                        map.put("status", "1");
                        map.put("customer_type",list.get(i).getCustomer_type()+"");
                        pressenter.sendMessage(context, Constant.modify_status, map, Bean.class);
                        Intent intent = new Intent(context, MsgActivity.class);
                        intent.putExtra("phone", list.get(i).getTel());
                        context.startActivity(intent);
                }


            }
        });

        viewHolder.img_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                switch (userType) {
                    case "0":
                        Toast.makeText(context, "暂无权限查看，请升级会员", Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(context, "您的会员已过期", Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "5":
                    default:

                        //权限没有获得
                        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                            // 不需要解释为何需要该权限，直接请求授权
                            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS}, 100);
                        } else {
                            // 已经获得授权
//                    Util.addContact(context,"小萌芽","18801586942");
                            String[] split = list.get(i).getTel().split(";");
                            for (int j = 0; j < split.length; j++) {
                                Util.addContact(context, list.get(i).getCompany_name() + (j + 1), split[j]);
                            }
                            Map<String, String> map = new HashMap<>();
                            map.put("token",Constant.TOKEN);
                            map.put("uid", uid);
                            map.put("type", "2");
                            map.put("customer_id", list.get(i).getCustomer_id() + "");
                            map.put("status", "1");
                            map.put("customer_type",list.get(i).getCustomer_type()+"");
                            pressenter.sendMessage(context, Constant.modify_status, map, Bean.class);
                            Toast.makeText(context, "导入成功", Toast.LENGTH_SHORT).show();

                        }
                }


            }
        });

        viewHolder.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onIntentClick.item(i);
            }
        });


    }

    private void CallPhone(int i) {
        String number = list.get(i).getTel();
        String[] split = number.split(";");

        if (number == null || number.equals("")) {
            Toast.makeText(context, "用户未填写手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(number)) {
            // 提醒用户
            Toast.makeText(context, "用户未填写手机号码", Toast.LENGTH_SHORT).show();
        } else {

            Map<String, String> map = new HashMap<>();
            map.put("token",Constant.TOKEN);
            map.put("uid", uid);
            map.put("type", "3");
            map.put("customer_id", list.get(i).getCustomer_id() + "");
            map.put("status", "1");
            map.put("customer_type",list.get(i).getCustomer_type()+"");
            pressenter.sendMessage(context, Constant.modify_status, map, Bean.class);


            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_DIAL); // 设置动作
            Uri data = Uri.parse("tel:" + split[0]); // 设置数据
            intent.setData(data);
            context.startActivity(intent); // 激活Activity组件
        }
    }


    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void requesta(Object data) {

    }

    @Override
    public void fail(String error) {

    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public CheckBox agree;
        public TextView name;
        public TextView phone;
        public TextView addr;
        public TextView del;
        public ImageView img_phone;
        public ImageView img_msg;
        public ImageView img_num;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            agree = itemView.findViewById(R.id.agree);
            name = itemView.findViewById(R.id.name);
            phone = itemView.findViewById(R.id.phone);
            addr = itemView.findViewById(R.id.addr);
            img_phone = itemView.findViewById(R.id.img_phone);
            img_msg = itemView.findViewById(R.id.img_msg);
            img_num = itemView.findViewById(R.id.img_num);
            del = itemView.findViewById(R.id.del);
        }
    }

    private OnClick onClick;

    public void setdeleteClick(OnClick onClick) {
        this.onClick = onClick;
    }

    public interface OnClick {
        void item(int posttion, boolean check);
    }

    private OnIntentClick onIntentClick;

    public void setaddClick(OnIntentClick onClick) {
        this.onIntentClick = onClick;
    }

    public interface OnIntentClick {
        void item(int position);
    }


}

